<template>
	<Skeleton v-if="loading"></Skeleton>
	<view class="container" v-else>
		<view style="height: 110rpx">
			<view class="header">
				<view class="shop-wrapper" @tap="navShop">
					<text class="icon-mendian iconfont" style="font-size: 35rpx"></text>
					<text>{{ shop.name }}</text>
					<text class="icon-qianwang iconfont" style="font-size: 30rpx; font-weight: bold"></text>
				</view>
				<view class="search-wrapper" @tap="navSearch">
					<uni-search-bar class="uni-mt-10 search-bar" radius="100" bgColor="#fff" placeholder="请输入内容" clearButton="none" cancelButton="none" readonly />
				</view>
			</view>
		</view>

		<view>
			<uni-notice-bar :speed="60" show-icon scrollable :text="shop.notice" />
		</view>

		<Banner :bannerList="bannerList"></Banner>

		<view class="content">
			<block v-for="(category, categoryIdx) in categoryList" :key="category.name" v-if="category.goodsList.length != 0">
				<view class="category">
					<text class="iconfont icon-bingtu category-icon"></text>
					<text class="category-name">{{ category.name }}</text>
				</view>
				<view class="goods-list">
					<view
						class="goods-item"
						v-for="(goods, goodsIdx) in category.goodsList"
						:key="goods.name"
						@tap="gotoGoodsDetail(goods.id)"
						:class="category.indexFlag == 1 ? 'goods-item-col-2' : 'goods-item-col-3'"
					>
						<view style="position: relative">
							<lazyLoad :src="goods.thumbnail" :column="category.indexFlag === 1 ? 2 : 3" :isEmpty="goods.stockNum === 0 ? true : false"></lazyLoad>
							<view class="sold-out-wrapper" v-if="goods.stockNum == 0">
								<view class="sold-out">
									<text>线上售罄</text>
									<view style="width: 100%; padding: 20rpx">
										<text class="line"></text>
									</view>
									<text>Sold out</text>
								</view>
							</view>
						</view>
						<view class="goods-name">
							{{ goods.name }}
						</view>
						<view class="goods-price">
							<text class="first">¥</text>
							<text class="second">{{ goods.minGoodsPrice.toFixed(2) }}</text>
						</view>
						<view class="line-price">
							<text class="first">¥</text>
							<text class="second">{{ goods.minLinePrice.toFixed(2) }}</text>
						</view>
						<view>
							<uni-badge
								@tap.stop="addCart(categoryIdx, goodsIdx)"
								:text="goods.cartNum"
								absolute="rightTop"
								size="small"
								style="position: absolute; right: 0; bottom: 0; padding: 20rpx"
							>
								<text class="iconfont .icon-cart-index cart-icon" :class="goods.stockNum == 0 ? 'cart-icon-sold-out' : ''"></text>
							</uni-badge>

							<DarkeCartsBall
								ref="cartBall"
								:ballImage="`url('${goods.thumbnail}')`"
								:duration="1000"
								:endPos="endPos"
								:zIndex="9999"
								ballColor="transparent"
								is3dSheet="false"
							></DarkeCartsBall>
						</view>
					</view>
				</view>
			</block>
		</view>
		<!-- 规格信息弹出层 -->
		<uni-popup ref="popup" class="popup" background-color="#fff">
			<GoodsPopup
				ref="goodsPopup"
				:popupGoods="popupGoods"
				:specType="specType"
				:specNameList="specNameList"
				:goodsDetailList="goodsDetailList"
				:goodsStockList="goodsStockList"
			></GoodsPopup>
		</uni-popup>
	</view>
</template>

<script>
import { listGoods, listBanner } from '@/api/index';
import { checkUser } from '@/api/user';
import { handleSubscript } from '@/utils/cart.js';
import Banner from '@/components/banner.vue';
import lazyLoad from '@/components/lazyLoad.vue';
import Skeleton from '@/components/skeleton.vue';
import GoodsPopup from '@/components/goods_popup.vue';
import DarkeCartsBall from '@/components/darke-cartsBall/darke-cartsBall.vue';
import { mapState, mapGetters } from 'vuex';
import goodsMixin from '@/mixins/goodsMixin';

export default {
	components: {
		Banner,
		Skeleton,
		GoodsPopup,
		DarkeCartsBall,
		lazyLoad
	},
	mixins: [goodsMixin],
	data() {
		return {
			loading: true,
			isCheckUser: false,
			bannerList: [],
			categoryList: [],
			goodsList: {},
			token: '',
			popupGoods: {},

			// 购物车动画飞入的终点
			endPos: {},
			ballGoodsIdx: 0,

			detailUrl: '/pages/goods_detail/goods_detail?goodsId=',
			navShopUrl: '/pages/shop/shop',
			navSearchUrl: '/pages/search/search'
		};
	},
	computed: {
		...mapState('goods', ['isPopupShow']),
		...mapState('cart', ['isAddSuccess']),
		...mapGetters(['shop'])
	},
	watch: {
		isPopupShow(newVal, oldVal) {
			const pages = getCurrentPages();
			// 不是自己不用处理
			if (pages[pages.length - 1].route != 'pages/index/index') {
				return;
			}
			if (!newVal) {
				/**
				 * 此时监听到show为false，关闭购物弹出层
				 * spec_popup.vue addCart()方法内将其置为false
				 */
				this.$refs.popup.close();

				// 将show重新置为true
				this.$store.dispatch('goods/handleGoodsPopupShow', true);
			}
		},
		isAddSuccess(newVal, oldVal) {
			const pages = getCurrentPages();
			// 不是自己不用处理
			if (pages[pages.length - 1].route != 'pages/index/index') {
				return;
			}
			if (newVal) {
				// 开启商品飞入动画
				this.cartBall();
				this.updateList();
				// 重新置为false
				this.$store.dispatch('cart/handleAddSuccess', false);
			}
		}
	},
	onLoad(query) {
		// const scene = decodeURIComponent(query.scene);
		const recommender = query.scene;
		if (recommender) {
			console.log(query);
			uni.setStorageSync('recommender', query.scene);
			this.isCheckUser = true;
		}
		// console.log('in user-ui, userId = ', scene);
	},
	onShareAppMessage(res) {},
	async onShow() {
		this.initData();
		if (this.isCheckUser) {
			console.log('开始检查user');
			const res = await checkUser();
			// 放一个res在这，会导致出错，不会执行后面的
			this.isCheckUser = false;
			console.log('结束检查user');
		}
		this.getBanner();
		this.getList();
		this.loading = false;
		handleSubscript();

		uni.getSystemInfo({
			success: (res) => {
				const screenWidth = res.windowWidth; // 屏幕宽度，单位为px
				const screenHeight = res.windowHeight; // 屏幕高度，单位为px
				this.endPos = {
					x: screenWidth * (2 / 3) - 30,
					y: screenHeight
				};
			}
		});
	},
	methods: {
		initData() {
			this.categoryList = [];
			this.goodsList = [];
		},
		/**
		 * 获取轮播图列表
		 */
		getBanner() {
			listBanner().then((res) => {
				this.bannerList = res.data;
			});
		},
		/**
		 * 获取位于首页的商品列表
		 */
		async getList() {
			// sql语句 index_flag != #{categoryNotIndexFlag}
			let params = {
				categoryNotIndexFlag: 0,
				goodsIndexFlag: 1
			};
			const res = await listGoods(params);
			console.log(res);
			this.categoryList = res.data.categoryList;
			this.goodsList = res.data.goodsList;
			this.updateList();
			for (let i = 0; i < this.categoryList.length; i++) {
				// 商品分类过滤
				this.categoryList[i].goodsList = this.goodsList.filter((item) => item.categoryId == this.categoryList[i].id);
			}
			console.log('category', this.categoryList);
			console.log('goodsList', this.goodsList);
		},
		/**
		 * 更新商品列表
		 * 更新购物车角标
		 */
		updateList() {
			this.goodsList.forEach((goods) => {
				goods.cartNum = this.$store.getters.getCartNum(goods.id);
			});
		},
		/**
		 * 加入购物车
		 * @param {Object} categoryIdx
		 * @param {Object} goodsIdx
		 */
		async addCart(categoryIdx, goodsIdx) {
			this.popupGoods = this.categoryList[categoryIdx].goodsList[goodsIdx];
			if (this.popupGoods.stockNum === 0) {
				return;
			}
			// 计算购物车图标的位置
			this.ballGoodsIdx = goodsIdx;
			for (let i = 0; i < categoryIdx; i++) {
				this.ballGoodsIdx += this.categoryList[i].goodsList.length;
			}

			const isPopupShow = await this.getGoodsSpecInfo(this.popupGoods.id);
			if (isPopupShow) {
				this.$refs.popup.open('bottom');
			} else {
				this.$refs.goodsPopup.addCart();
			}
			this.updateList();
		},
		/**
		 * 跳转到商品详情页面
		 * @param {Object} goodsId 商品id
		 */
		gotoGoodsDetail(goodsId) {
			uni.navigateTo({
				url: this.detailUrl + goodsId
			});
		},
		navShop() {
			uni.navigateTo({
				url: this.navShopUrl
			});
		},
		navSearch() {
			console.log('focus');
			uni.navigateTo({
				url: this.navSearchUrl
			});
		}
	}
};
</script>

<style>
page {
	background-color: #f9f9f9;
}
.uni-searchbar__box {
	height: 65rpx !important;
}
.uni-noticebar {
	background-color: unset !important;
	padding: 10rpx 24rpx !important;
}
</style>

<style scoped lang="less">
@theme-color: #ff5a14;
@col-2-icon: 40rpx;
@col-3-icon: 28rpx;

.header {
	position: fixed;
	z-index: 100;
	left: 0;
	top: 0;
	width: 100%;
	height: 110rpx;

	display: flex;
	align-items: center;
	padding-left: 20rpx;
	background-color: #f5f5f5;
	.shop-wrapper {
		display: flex;
		align-items: center;
		column-gap: 10rpx;
		color: #515a6e;
		font-size: 28rpx;
	}
	.search-wrapper {
		flex: 1;
		.search-bar {
		}
	}
}

.container .index-swiper {
	padding: 15rpx;
}

.container .content .category {
	display: flex;
	flex-direction: row;
	align-items: center;
	gap: 20rpx;
	padding: 20rpx 15rpx;
	font-size: 30rpx;

	.category-icon {
		font-size: 40rpx;
		color: #ea3a46;
		transform: rotate(30deg);
	}

	.category-name {
		font-weight: bold;
	}
}

.container .content .goods-list {
	display: flex;
	flex-direction: row;
	flex-wrap: wrap;
	padding: 10rpx 15rpx;
	gap: 16rpx;

	.goods-item {
		position: relative;
		display: flex;
		flex-direction: column;
		background-color: #fff;
		border-radius: 12rpx;

		.goods-name,
		.goods-price,
		.line-price {
			padding: 0 10rpx;
		}

		.goods-name {
			padding-top: 10rpx;
			padding-bottom: 50rpx;
		}

		.goods-price,
		.line-price {
			color: @theme-color;
			padding-top: 5rpx;
			padding-bottom: 5rpx;
			font-weight: bold;
		}

		.line-price {
			opacity: 0.5;
			text-decoration: line-through;
		}

		.cart-icon {
			display: block;
			background-color: #fff;
			padding: 5rpx;
			border: 1rpx solid @theme-color;
			border-radius: 50%;
			font-size: 35rpx;
			color: @theme-color;
		}

		.cart-icon-sold-out {
			color: #999999;
			border: 0;
		}
	}

	// 计算得出： (750 - 30(padding) - 16(gap)) / (2
	.goods-item-col-2 {
		width: 352rpx;
		font-size: 30rpx;

		.cart-icon {
			font-size: @col-2-icon;
		}

		.goods-price > .first {
			font-size: 25rpx;
			margin-right: 5rpx;
		}
		.goods-price > .second {
			font-size: 32rpx;
		}
		.line-price > .first {
			font-size: 20rpx;
			margin-right: 5rpx;
		}
		.line-price > .second {
			font-size: 25rpx;
		}
	}

	// 计算得出： (750 - 30(padding) - 32(gap)) / 3
	.goods-item-col-3 {
		width: 229rpx;
		font-size: 25rpx;

		.cart-icon {
			font-size: @col-3-icon;
		}

		.goods-price > .first {
			font-size: 20rpx;
			margin-right: 5rpx;
		}
		.goods-price > .second {
			font-size: 25rpx;
		}
		.line-price > .first {
			font-size: 15rpx;
			margin-right: 5rpx;
		}
		.line-price > .second {
			font-size: 20rpx;
		}
	}
}
</style>
